import fetch from './fetch';

type DAO<T> = {
  code: number;
  hint: string;
  data: T;
};

export default {
  GET<T = any>(path: string, headers?: any) {
    return fetch<DAO<T>>(path, 'GET', undefined, headers).then(
      ({ code, hint, data }) => {
        if (code === 0) {
          return data;
        }
        throw hint;
      }
    );
  },
  POST<T = any>(path: string, data?: any, headers?: any) {
    return fetch<DAO<T>>(path, 'POST', data, headers).then(
      ({ code, hint, data }) => {
        if (code === 0) {
          return data;
        }
        throw hint;
      }
    );
  },
  PUT<T = any>(path: string, data?: any, headers?: any) {
    return fetch<DAO<T>>(path, 'PUT', data, headers).then(
      ({ code, hint, data }) => {
        if (code === 0) {
          return data;
        }
        throw hint;
      }
    );
  },
  DELETE<T = any>(path: string, headers?: any) {
    return fetch<DAO<T>>(path, 'DELETE', undefined, headers).then(
      ({ code, hint, data }) => {
        if (code === 0) {
          return data;
        }
        throw hint;
      }
    );
  },
};
